package uit.nfcmenu.util;

import java.io.File;

import android.content.Context;
import android.util.Log;

public class FileCache {
	static String tag = FileCache.class.getSimpleName();

	private File cacheDir;

	public FileCache(Context context) {
		// Find the dir to save cached images
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			cacheDir = new File(CommConstant.SDCARD_PATH);
		} else {
			cacheDir = context.getCacheDir();
		}
		if (!cacheDir.exists()) {
			cacheDir.mkdirs();
		}
	}

	public static String getImgPngFromUrl(String url) {
		String fileName = url.substring(url.lastIndexOf("/"));
		
		fileName = fileName.replace("serve?blob-key=", "");
		if (!url.endsWith(".png")) {
			fileName += ".png";
		}
		Log.w(tag, "fileName="+fileName);
		return fileName;
	}
	
	public File getFilePNG(String url) {
		// images by hashcode. Not a perfect solution,

		// String filename=String.valueOf(url.hashCode());
		try {
			String fileName = getImgPngFromUrl(url);
			File f = new File(cacheDir, fileName);
			return f;
		} catch (Exception e) {
			return null;
		}
	}

	public void clear() {
		File[] files = cacheDir.listFiles();
		if (files == null)
			return;
		for (File f : files)
			f.delete();
	}

//	Environment.getExternalStorageDirectory()
//    + File.separator + "visualmenu/menu_..."...
	public static String getMenuSDCardUri(int id) {
		return CommConstant.SDCARD_PATH + "menu_" + id + ".png";
	}

	public static String getItemSDCardUri(int id) {
		return CommConstant.SDCARD_PATH + "item_" + id + ".png";
	}
	
	public static String getMenuSDCardUri(String name) {
		name = getFullImageName(name);
		return CommConstant.SDCARD_PATH + "menu_" + name;
	}

	public static String getItemSDCardUri(String name) {
		name = getFullImageName(name);
		return CommConstant.SDCARD_PATH + "item_" + name;
	}
	
	private static String getFullImageName(String name) {
		if (!name.endsWith(".png") || name.endsWith(".jpg")) {
			name += ".png";
		}
		return name;
	}
}